<template>
	<page-bg :showTitle="!isWrite">
		<view v-if="!isWrite" class="top-head">
			{{ $t('verification.welcome.title') }}<br />
			{{ $t('verification.welcome.subtitle') }}
		</view>

		<!-- 获取验证码 -->
		<view class="form" v-if="!isWrite">
			<view class="input-group">
				<view class="area-code flex-item-center">
					<!-- +86 <image src="@/static/down-icon.png"></image> -->
					<picker class="area-code flex-item-center" :value="areaCodeIndex" :range="areaCodes"
						range-key="display" @change="onAreaCodeChange">
						{{ currentAreaCode.zone }}
						<image src="@/static/down-icon.png"></image>
					</picker>
				</view>
				<input type="number" v-model="phone" :placeholder="$t('verification.placeholders.phone')" class="input"
					@input="handlePhoneInput" />
				<button class="sure-btn" @click="handleSureClick" :class="{ 'lighten-btn': !isFormValid }">
					{{ $t('verification.buttons.sure') }}
				</button>
			</view>

			<view class="verification-box">
				<liu-slider-verify ref="verify" @change="handleSliderChange" sBgColor="#52A5F3"></liu-slider-verify>
			</view>

			<view class="agreement" @click="isChecked=!isChecked">
				<uni-icons v-if="!isChecked" class="icons" type="circle" :size="16" color="#4D7AA5"></uni-icons>
				<uni-icons v-else class="icons" type="checkbox-filled" :size="16" color="#52A5F3"></uni-icons>
				<text>{{ $t('verification.agreement.prefix') }}</text>
				<text class="link">{{ $t('verification.agreement.terms') }}</text>
				<text>{{ $t('verification.agreement.suffix') }}</text>
			</view>
		</view>

		<!-- 输入验证码 -->
		<view v-else class="verification-form">
			<uni-icons class="left-icon" type="left" :size="32" color="#fff" @click="isWrite=false"></uni-icons>
			<view class="write-verification">
				<view class="title">{{ $t('verification.code.title') }}</view>
				<view class="sub-title">
					{{ $t('verification.code.subtitle') }}<text>+{{ currentAreaCode.code }} {{ formattedPhone }}</text>
				</view>
				<view class="input-box flex-item-center">
					<input v-for="(digit, index) in code" :key="index" type="number" maxlength="1" v-model="code[index]"
						:ref="'codeInput' + index" :id="'codeInput' + index" @input="handleCodeInput(index)"
						@keyup="handleKeyUp($event, index)" />
				</view>
			</view>
			<view class="tips">
				<span v-if="countdown > 0">
					{{ countdown }} {{ $t('verification.code.countdownTips') }}
				</span>
				<span v-else>
					<text @click="resendCode" class="resend-link">
						{{ $t('verification.code.resend') }}
					</text>
				</span>
			</view>
		</view>
	</page-bg>
</template>

<script>
	import PageBg from '@/pages/components/page-bg/page-bg.vue';
	import loginApi from '@/api/login.js';
	import LiuSliderVerify from '@/uni_modules/liu-slider-verify/components/liu-slider-verify/liu-slider-verify.vue';

	export default {
		components: {
			PageBg,
			LiuSliderVerify
		},
		data() {
			return {
				phone: '',
				isChecked: false,
				isWrite: false,
				sliderVerified: false,
				code: ['', '', '', ''],
				countdown: 0,
				timer: null,
				// 新增：国家区号数据
				areaCodes: [{
						code: 86,
						zone: "+86",
						display: "+86(中国)"
					},
					{
						code: 1,
						zone: "+1",
						display: "+1(美国)"
					},
					{
						code: 44,
						zone: "+44",
						display: "+44(英国)"
					},
					{
						code: 81,
						zone: "+81",
						display: "+81(日本)"
					},
					{
						code: 82,
						zone: "+82",
						display: "+82(韩国)"
					},
					{
						code: 65,
						zone: "+65",
						display: "+65(新加坡)"
					}
				],
				areaCodeIndex: 0, // 当前选中的区号索引
			};
		},
		computed: {
			// 当前选中的区号对象
			currentAreaCode() {
				return this.areaCodes[this.areaCodeIndex];
			},
			isFormValid() {
				const phoneValid = /^1[3-9]\d{9}$/.test(this.phone);
				return phoneValid && this.sliderVerified && this.isChecked;
			},
			formattedPhone() {
				return this.phone ? this.phone.slice(-4) : '';
			},
			// 新增：完整的手机号（带区号）
			fullPhoneNumber() {
				return `+${this.currentAreaCode.code} ${this.phone}`;
			}
		},
		methods: {

			// 新增：处理区号变更
			onAreaCodeChange(e) {
				this.areaCodeIndex = e.detail.value;
			},
			handlePhoneInput() {
				this.phone = this.phone.replace(/\D/g, '').slice(0, 11);
			},

			handleSliderChange(e) {
				this.sliderVerified = e.state;
				if (e.state) {
					uni.showToast({
						title: '滑块验证通过',
						icon: 'success'
					});
				}
			},

			focusInput(index) {
				const inputRef = this.$refs[`codeInput${index}`];
				if (inputRef && inputRef[0]) {
					uni.createSelectorQuery()
						.select(`#codeInput${index}`)
						.fields({
							node: true
						}, (res) => {
							if (res && res.node) {
								res.node.focus();
								res.node.select();
							} else {
								console.error(`无法聚焦输入框 ${index}: 元素未找到`);
							}
						})
						.exec();
				} else {
					console.error(`无法聚焦输入框 ${index}: 引用不存在`);
				}
			},

			handleSureClick() {
				if (!this.isFormValid) {
					let errorMsg = '';
					if (!/^1[3-9]\d{9}$/.test(this.phone)) {
						errorMsg = '请输入有效的手机号码';
					} else if (!this.sliderVerified) {
						errorMsg = '请完成滑块验证';
					} else if (!this.isChecked) {
						errorMsg = '请同意协议';
					}
					uni.showToast({
						title: errorMsg,
						icon: 'none'
					});
					return;
				}

				this.startCountdown();
				this.isWrite = true;

				this.$nextTick(() => {
					this.focusInput(0);
				});
			},

			handleCodeInput(index) {
				this.code[index] = this.code[index].replace(/\D/g, '').slice(0, 1);
				if (this.code[index] && index < 3) {
					this.focusInput(index + 1);
				}
				if (index === 3 && this.code[index]) {
					this.handleCodeSubmit();
				}
			},

			handleKeyUp(event, index) {
				// 兼容性检查，确保 event 存在
				if (!event || !event.detail) {
					console.error(`handleKeyUp: 事件对象未定义或缺少 detail 属性`, event);
					return;
				}

				// 在 UniApp 中，key 可能在 event.detail.key 或直接在 event.key 中
				const key = event.detail?.key || event.key;
				if (key === 'Backspace' && !this.code[index] && index > 0) {
					this.code[index - 1] = '';
					this.focusInput(index - 1);
				}
			},

			handleFocus(index) {
				this.focusInput(index);
			},

			handleCodeSubmit() {
				const code = this.code.join('');
				if (code.length !== 4 || !/^\d{4}$/.test(code)) {
					uni.showToast({
						title: '请输入4位数字验证码',
						icon: 'none'
					});
					return;
				}

				uni.showLoading({
					title: '正在验证...'
				});

				setTimeout(() => {
					uni.hideLoading();
					uni.showToast({
						title: '验证码验证成功',
						icon: 'success'
					});
					uni.navigateTo({
						url: '/pages/my/wallet/wallet'
					});
				}, 1000);
			},

			startCountdown() {
				this.countdown = 60;
				if (this.timer) clearInterval(this.timer);
				this.timer = setInterval(() => {
					if (this.countdown > 0) {
						this.countdown--;
					} else {
						clearInterval(this.timer);
					}
				}, 1000);
			},

			resendCode() {
				if (this.isFormValid) {
					this.startCountdown();
					uni.showToast({
						title: '验证码已重新发送',
						icon: 'none'
					});
					this.code = ['', '', '', ''];
					this.$nextTick(() => {
						this.focusInput(0);
					});
				} else {
					uni.showToast({
						title: '请先完成验证',
						icon: 'none'
					});
				}
			},

			reset() {
				this.$refs.verify.initialization();
				this.sliderVerified = false;
			}
		},
		beforeDestroy() {
			if (this.timer) clearInterval(this.timer);
		}
	};
</script>

<style lang="less" scoped>
	.top-head {
		margin: 58rpx 24rpx 80rpx 0;
		text-align: right;
		color: #52A5F3;
		font-size: 48rpx;
		line-height: 64rpx;
	}

	.form {
		width: 100%;
		padding: 0 68rpx;
		font-size: 28rpx;
	}

	.area-code {
		position: absolute;
		top: 50%;
		transform: translateY(-50%);
		left: 16rpx;
		color: #52A5F3;
		font-weight: 500;
		width: 160rpx;
		text-align: left;
		text-overflow: ellipsis;
		white-space: nowrap;

		image {
			margin-left: 10rpx;
			width: 18rpx;
			height: 14rpx;
		}
	}

	.input-group {
		margin-top: 40rpx;
		position: relative;
		overflow: hidden;
		background-color: #fff;
		border-radius: 54px;

		input {
			padding: 0 158rpx 0 144rpx;
			font-size: 28rpx;
			height: 98rpx;
			line-height: 98rpx;
			width: 100%;
		}
	}

	.sure-btn {
		position: absolute;
		top: 0;
		right: 0;
		width: 158rpx;
		height: 100%;
		line-height: 98rpx;
		background-color: #52A5F3;
		color: #1D6BB4;
		font-size: 28rpx;
		border-radius: 0;

		&.lighten-btn {
			background-color: #E0F0FF;
			color: #90CAF9;
			pointer-events: none;
		}
	}

	.verification-box {
		margin-top: 30rpx;
		width: 100%;
		height: 72rpx;
		background-color: #fff;
		border-radius: 50rpx;
		position: relative;
		overflow: hidden;

		.slider-verify {
			height: 100%;
		}

		/deep/ .movable-btn {
			border: none;
		}

		/deep/ .slider-prompt {
			opacity: 0;
		}
	}

	.agreement {
		font-size: 24rpx;
		color: #fff;
		text-align: center;
		margin-top: 68rpx;
		line-height: 40rpx;

		.icons {
			margin-right: 10rpx;
		}
	}

	.left-icon {
		position: absolute;
		top: 78rpx;
		left: 20rpx;
	}

	.verification-form {
		margin-top: 242rpx;
		padding: 0 42rpx;
	}

	.write-verification {
		height: 460rpx;
		padding: 44rpx 45rpx;
		background-color: #fff;
		border-radius: 30rpx;
		text-align: center;

		.title {
			margin-bottom: 26rpx;
			font-size: 44rpx;
			line-height: 60rpx;
		}

		.sub-title {
			font-size: 28rpx;
			color: #666;

			text {
				color: #52A5F3;
			}
		}

		.input-box {
			margin-top: 50rpx;

			input {
				margin-right: 10rpx;
				width: 136rpx;
				height: 136rpx;
				background: url('/static/input-bg.png') no-repeat;
				background-size: 100%;
				text-align: center;
				font-size: 48rpx;
				border: none;
				outline: none;

				&:last-child {
					margin-right: 0;
				}
			}
		}
	}

	.tips {
		margin-top: 44rpx;
		color: #52A5F3;
		font-size: 32rpx;
		line-height: 48rpx;
		text-align: center;

		.resend-link {
			text-decoration: underline;
			cursor: pointer;
		}
	}
</style>